package com.baoyouqun.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baoyouqun.API.wx.WechatApiUtil;
import com.baoyouqun.base.SystemConstant;
import com.baoyouqun.base.utils.ConvertUtils;
import com.baoyouqun.domain.VO.UserVO;
import com.baoyouqun.domain.cmd.LoginCmd;
import com.baoyouqun.entity.User;
import com.baoyouqun.service.LoginService;
import com.baoyouqun.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private WechatApiUtil wechatApiUtil;


    @Override
    public SingleResponse<String> login(LoginCmd cmd) {
        long loginTotalStart = System.currentTimeMillis();


        // 1. 查询用户（已监控耗时）
        User user = userService.selectByCellphone(cmd.getCellphone());
        if (user == null) {
            return SingleResponse.buildFailure("30001", "用户不存在");
        }
//        if (Objects.isNull(user.getBackWorker()) || !user.getBackWorker().equals(Boolean.TRUE)) {
//            return SingleResponse.buildFailure("30001", "用户非后台用户");
//        }

        // 2. 验证密码（BCrypt匹配，正常<100ms）
        long passwordStart = System.currentTimeMillis();
        if (!passwordEncoder.matches(cmd.getPassword(), user.getPassword())) {
            return SingleResponse.buildFailure("30002", "密码错误");
        }

        // 3. Sa-Token登录（会话创建+token生成）
        long saTokenStart = System.currentTimeMillis();
        StpUtil.login(user.getId());
        String token = StpUtil.getTokenValue();
        StpUtil.getSession().set(SystemConstant.SA_TOKEN_USER_INFO, ConvertUtils.copyBean(user, UserVO.class));
        StpUtil.getSession().set(SystemConstant.SA_TOKEN_USER_ID, user.getId());

        return SingleResponse.of(token);
    }

    @Override
    public Response logout() {
        StpUtil.logout();
        return Response.buildSuccess();
    }

    /*处理微信登录，更新session_key*/
/*    @Override
    public SingleResponse<WxUserLoginVO> wechatLogin(String code) {
        // 1. 调用微信接口换取session_key和openid
        JSONObject sessionInfo = wechatApiUtil.getSessionInfo(code);
        // 检查微信返回是否有错误
        if (sessionInfo.containsKey("errcode") && sessionInfo.getIntValue("errcode") != 0) {
            return SingleResponse.buildFailure("600808", "微信登录失败：" + sessionInfo.getString("errmsg"));
        }
        log.info("sessionInfo:{}", JSONObject.toJSONString(sessionInfo));
        // 2. 解析返回结果
        String openid = sessionInfo.getString("openid");
        String sessionKey = sessionInfo.getString("session_key");
        String unionid = sessionInfo.getString("unionid");  // 可选

        // 3. 根据openid查询用户
        User user = userService.selectByWxOpenid(openid);
        if (user == null) {
            return SingleResponse.buildFailure("50404", "用户未绑定微信，请先绑定, 后续重定向至前端注册登录页面:openid:" + openid);
        }

        boolean updateRes = userService.updateSessionKey(openid, sessionKey);
        if (!updateRes) {
            return SingleResponse.buildFailure("30002", "更新SessionKey失败，请重新登录");
        }
        User userNew = userService.selectByWxOpenid(openid);
        if (userNew == null) {
            return SingleResponse.buildFailure("30002", "用户未绑定微信，请先绑定, 后续重定向至前端注册登录页面:openid:" + openid);
        }
        long saTokenStart = System.currentTimeMillis();
        StpUtil.login(user.getId());
        String token = StpUtil.getTokenValue();
        StpUtil.getSession().set(SystemConstant.SA_TOKEN_USER_INFO, ConvertUtils.copyBean(user, UserVO.class));
        StpUtil.getSession().set(SystemConstant.SA_TOKEN_USER_ID, user.getId());
        WxUserLoginVO wxUserLoginVO = new WxUserLoginVO(userNew.getId(), userNew.getName(), userNew.getWxOpenid(), userNew.getWxName(), token);
        return SingleResponse.of(wxUserLoginVO);
    }
    // 调用 jscode2session 接口，兑换 openid 和 session_key
    public String getSessionInfo(String jsCode) {
        // 1. 构造请求 URL（拼接所有参数）
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appid, secret, jsCode
        );

        // 2. 发起 GET 请求（推荐用 OkHttp 或 RestTemplate）
        RestTemplate restTemplate = new RestTemplate();
        try {
            String response = restTemplate.getForObject(url, String.class);
            log.info("jscode2session 返回结果：{}", response);
            return response; // 返回给前端（实际项目需解析 JSON 并处理）
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("微信登录失败：" + e.getMessage());
        }
    }
*/


    /**
     * 根据openid获取有效的session_key（用于解密敏感数据）
     */
    @Override
    public SingleResponse<String> getValidSessionKey(String openid) {
        User user = userService.selectByWxOpenid(openid);
        if (user == null) {
            return SingleResponse.buildFailure("30002", "用户未绑定微信，请先绑定");
        }
        // 检查session_key是否过期
        if (user.getWxSessionExpire() == null ||
                user.getWxSessionExpire().isBefore(LocalDateTime.now())) {
            throw new RuntimeException("session_key已过期，请重新登录");
        }

        return SingleResponse.of(user.getWxSessionKey());
    }


}
